package com.forezp.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @desc
 * pre：路由之前
 * routing：路由之时
 * post： 路由之后
 * error：发送错误调用
 * filterOrder：过滤的顺序
 *s houldFilter：这里可以写逻辑判断，是否要过滤，本文true,永远过滤。
 * run：过滤器的具体逻辑。可用很复杂，包括查sql，nosql去判断该请求到底有没有权限访问。
 * @by yangfei
 * @create 2017-9-12 13:37
 */
@Component
public class MyFilter extends ZuulFilter{
    private static  Logger log = LoggerFactory.getLogger(MyFilter.class);

    public String filterType() {
        return "pre";
    }

    public int filterOrder() {
        return 0;
    }

    /**
     * @desc 开启指标检查
     * @return
     */
    public boolean shouldFilter() {
        return true;
    }

    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest httpServletRequest = requestContext.getRequest();
        log.info(String.format("%s >>> %s", httpServletRequest.getMethod(), httpServletRequest.getRequestURL().toString()));
        Object accessToken = httpServletRequest.getParameter("token");
        if (accessToken ==  null){
            log.warn("token 不能为空!");
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            try {
                requestContext.getResponse().getWriter().write("token 为空!");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        log.info("ok");
        return null;
    }
}
